﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.Globalization;

namespace SmartWarehouse
{
    namespace Common
    {

        /// <summary>
        /// Summary description for ExcelExporter
        /// </summary>
        public class ExcelExporter
        {
            public ExcelExporter()
            {
                //
                // TODO: Add constructor logic here
                //
            }

            /// <summary>
            /// Export the excel using HttpResponse
            /// </summary>
            /// <param name="httpResponse">Current HttpResponse</param>
            /// <param name="dataSource">Data source that be exported as MS Excel</param>
            /// <param name="exportedExcelName">The name of exported MS Excel</param>
            public static void Export(HttpResponse httpResponse, DataTable dataSource, string exportedExcelName)
            {
                //Create a fake GridView
                GridView gvExport = new GridView();
                gvExport.DataSource = dataSource;
                gvExport.DataBind();


                //Define http heah information
                httpResponse.Clear();
                httpResponse.Buffer = true;
                httpResponse.Charset = "utf-8";
                httpResponse.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", exportedExcelName));
                httpResponse.ContentEncoding = System.Text.Encoding.UTF8;
                httpResponse.ContentType = "application/ms-excel";

                //Export as MS Excel
                StringWriter strWriter = new StringWriter(new CultureInfo("zh-CN"));
                strWriter.WriteLine("<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=UTF-8\"/>");
                HtmlTextWriter htw = new HtmlTextWriter(strWriter);
                gvExport.RenderControl(htw);
                httpResponse.Output.Write(strWriter.ToString());
                httpResponse.Flush();
                httpResponse.End();
            }
        }
    }
}